<script setup lang="ts">
import { ref, onMounted,defineEmits,reactive } from 'vue'
import {try_login} from './login'
import { UseLibraryState } from '../library_state';
import {  ElNotification, FormRules,FormInstance } from "element-plus";

const emits=defineEmits(['cancelled','completed'])
const form_ref=ref<FormInstance>()

const user=reactive({
  nickname:'',
  password:''
})
const state=UseLibraryState()
const rules = reactive<FormRules>({
  nickname: [{ required: true, type:'string', message: "昵称不能为空!"}],
  password: [
    { required: true, type: "string", message: "密码不能为空!" },
  ],
});
onMounted(()=>{
    form_ref.value?.resetFields();
})

const login=async ()=>{
  if (!(user.nickname && user.password)) {
    ElNotification.warning({
      message:'请输入昵称和密码!',
      title:'Warning',
      duration:10000,
    })
    return
  }
  try {
    const _user=await try_login(user.nickname,user.password)
    state.loggedIn(_user)
    ElNotification.success({
      message:'登录成功:'+_user.nickName,
      title:'Success',
      duration:5000,
    })
    emits('completed')
  } catch (error) {
    ElNotification.error({
      message:'登录失败!\n'+error,
      title:'Error',
      duration:10000,
    })
  }
}
</script>

<template>
<div class="w-full h-full flex flex-col items-center">
  <h1 class="text-4xl text-gray-500 font-extrabold tracking-widest">LOGIN</h1>
  <el-form
  :model="user"
  style="width: 300px;"
  label-position="top"
  :rules="rules"
  ref="form_ref">
      <el-form-item label="昵称" prop="nickname">
      <el-input v-model="user.nickname" clearable/>
    </el-form-item>
          <el-form-item label="密码" prop="password">
      <el-input type="password" v-model="user.password" clearable/>
    </el-form-item>
    <div>
      <el-button type="primary" @click="login()">确认</el-button>
      <el-button type="danger" @click="emits('cancelled')">取消</el-button>
    </div>
  </el-form>
</div>
</template>

<style scoped>
.col-2{
  grid-template-columns: 6rem 1fr;
}
.login-container{
  transition: all 1s ease-in-out;
}
.hidden{
  transition: all 1s ease-in-out;
  transform: translateX(100%) scale(0);
}
</style>
<style>

</style>
